import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:intl/intl.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:package_info/package_info.dart';
import 'package:flutter_downloader/flutter_downloader.dart';

class UpdateApp extends StatefulWidget {
  final bool showButton;
  UpdateApp({this.showButton = false});
  @override
  _UpdateAppState createState() => _UpdateAppState();
}

class _UpdateAppState extends State<UpdateApp> {
  Response response;
  Dio dio = new Dio();
  bool needUpdate = false;
  PackageInfo packageInfo;
  final DateFormat formatterYear = new DateFormat('yyyy-MM-dd HH:mm');

  @override
  void initState() {
    super.initState();
    clickUpdateHandler();
  }

  checkNeedUpdate() async {
    response = await dio.get(
        "http://api.fir.im/apps/latest/5d75cc6ef94548120c2348b1?api_token=49ed60e38e83dfee341405aeaf480514");
    String _buildNumber = response.data['build'].toString();
    packageInfo = await PackageInfo.fromPlatform();
    String buildNumber = packageInfo.buildNumber;
    return num.parse(_buildNumber) > num.parse(buildNumber);
  }

  clickUpdateHandler() async {
    needUpdate = await checkNeedUpdate();
    if (needUpdate) {
      try {
        await showDialog<bool>(
          context: context,
          builder: (context) {
            return UpdateWindow(
              packageInfo: packageInfo,
              newVersion: response.data,
            );
          },
        );
      } catch (e) {}
    } else {
      return;
      await showDialog<bool>(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text(
                "当前软件已经是最新的版本,版本号: ${response.data['versionShort']} + ${response.data['build']}"),
            actions: <Widget>[
              RaisedButton(
                child: Text(
                  "取消",
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    if (!widget.showButton) return Container();
    return IconButton(
      onPressed: () async {
        try {
          await clickUpdateHandler();
        } catch (e) {
          await showDialog<bool>(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: Text("错误"),
                content: Text(e.toString()),
                actions: <Widget>[
                  RaisedButton(
                    child: Text(
                      "关闭",
                      style: TextStyle(color: Colors.white),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop(true);
                    },
                  ),
                ],
              );
            },
          );
        }
      },
      icon: Icon(
        Icons.sync,
        color: Colors.black,
      ),
    );
  }
}

class UpdateWindow extends StatefulWidget {
  final PackageInfo packageInfo;
  var newVersion;
  UpdateWindow({this.packageInfo, this.newVersion});
  @override
  _UpdateWindowState createState() => _UpdateWindowState();
}

class _UpdateWindowState extends State<UpdateWindow> {
  final DateFormat formatterYear = new DateFormat('yyyy-MM-dd HH:mm');
  int process;
  Future<bool> _checkPermission() async {
    final platform = Theme.of(context).platform;
    if (platform == TargetPlatform.android) {
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);
      if (permission != PermissionStatus.granted) {
        Map<PermissionGroup, PermissionStatus> permissions =
            await PermissionHandler()
                .requestPermissions([PermissionGroup.storage]);
        if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
          return true;
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
    return false;
  }

  @override
  void initState() {
    super.initState();
//taskId为任务id （与完成下载的文件成一一对应）open是执行打开 打开需要任务id 相信你已经找到方向了
    FlutterDownloader.registerCallback((taskId, status, _progress) {
      setState(() {
        process = _progress;
      });
      if (status == DownloadTaskStatus.complete) {
//下载完成

        Navigator.of(context).pop(true);
        FlutterDownloader.open(taskId: taskId);
      } else if (status == DownloadTaskStatus.failed) {
//下载出错
        Navigator.of(context).pop(true);
        toast('下载出错');
        print('下载出错');
      }
    });
  }

  @override
  void dispose() {
    FlutterDownloader.registerCallback(null);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final PackageInfo packageInfo = widget.packageInfo;
    var newVersion = widget.newVersion;

    String version = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;
    String changelog = newVersion['changelog'];
    if (newVersion['changelog'] == null ||
        newVersion['changelog'].toString().isEmpty) {
      changelog = '';
    }
    if (process != null) {
      return Material(
        color: Colors.transparent,
        child: Container(
          child: Center(
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 60.0, horizontal: 80.0),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(4.0)),
                color: Colors.white,
              ),
              child: new Container(
                //限制进度条的高度
                height: 40.0,
                //限制进度条的宽度
                width: 40,
                child: new CircularProgressIndicator(
                  //0~1的浮点数，用来表示进度多少;如果 value 为 null 或空，则显示一个动画，否则显示一个定值
                  value: process / 100,
                  //背景颜色
                  backgroundColor: Colors.grey,
                  //进度颜色
                  // valueColor: new AlwaysStoppedAnimation<Color>(Colors.red)
                ),
              ),
            ),
          ),
        ),
      );
    }

    return AlertDialog(
      title: Text("升级提示"),
      content: Text.rich(
        TextSpan(children: [
          TextSpan(
              text:
                  "发现新版本：${newVersion['versionShort']} + ${newVersion['build']}\n"),
          TextSpan(text: "当前版本：$version + $buildNumber\n"),
          TextSpan(
              text:
                  "发布日期：${formatterYear.format(new DateTime.fromMillisecondsSinceEpoch(newVersion['updated_at'] * 1000))}\n"),
          TextSpan(text: "更新内容：\n  $changelog")
        ]),
      ),
      actions: <Widget>[
        FlatButton(
          child: Text("取消"),
          onPressed: () => Navigator.of(context).pop(), // 关闭对话框
        ),
        RaisedButton(
          child: Text(
            "点击升级",
            style: TextStyle(color: Colors.white),
          ),
          onPressed: () async {
            _checkPermission().then((hasGranted) async {
              await FlutterDownloader.cancelAll();
              String taskId = await FlutterDownloader.enqueue(
                url: newVersion['installUrl'], //服务端提供apk文件下载路径
                savedDir: (await getExternalStorageDirectory())
                    .path
                    .toString(), //本地存放路径
                fileName: "shuzhiIm-${newVersion['updated_at']}.apk", //存放文件名
                showNotification: true, //是否显示在通知栏
                openFileFromNotification: true, //是否在通知栏可以点击打开此文件
              );
            });
          },
        ),
      ],
    );
  }
}
